<template>
  <div>
    <vxe-toolbar style="margin-bottom: 10px">
      <template #buttons>
        <vxe-button
          status="primary"
          icon="vxe-icon-square-plus"
          @click="insertEvent"
          >新增</vxe-button
        >
        <vxe-button
          status="primary"
          icon="vxe-icon-download"
          @click="exportData"
          >导出所有数据</vxe-button
        >
        <vxe-button
          status="primary"
          icon="vxe-icon-download"
          @click="generateReport"
          >导出PDF</vxe-button
        >
        <vxe-button
          status="primary"
          icon="vxe-icon-download"
          @click="exportDataEvent"
          >导出其他格式文件</vxe-button
        >
      </template>
    </vxe-toolbar>
    <vxe-table
      :loading="loading"
      ref="xTable"
      height="500"
      max-height="500"
      show-overflow
      :export-config="{}"
      border="full"
      :scroll-y="{ gt: 0 }"
      align="center"
      :row-config="{ isHover: true, height: 100 }"
      :column-config="{ resizable: true }"
      :data="tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="receiverName" title="用户名" width="80"></vxe-column>
      <vxe-column field="createTime" title="创建时间" width="200"></vxe-column>
      <vxe-column title="地址">
        <template #default="{ row }">
          <div v-html="row.receiverAddress"></div>
        </template>
      </vxe-column>
      <vxe-column field="status" title="发货状态" width="100"></vxe-column
      ><vxe-column field="totalPrice" title="订单金额" width="100"></vxe-column>
      <vxe-column width="200" title="操作">
        <template #default="{ row }">
          <vxe-button
            status="primary"
            icon="vxe-icon-info-circle-fill"
            @click="Details(row)"
          ></vxe-button>
          <vxe-button
            status="primary"
            icon="vxe-icon-edit"
            @click="recompose(row)"
          ></vxe-button>
          <el-popconfirm
            :title="`确认删除${row.title}吗？`"
            @confirm="deleteNewsList(row.id)"
          >
            <template #reference>
              <vxe-button status="danger" icon="vxe-icon-delete"></vxe-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="page"
      v-model:page-size="limit"
      :page-sizes="[20, 40, 60]"
      :small="false"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="(val: number) => getNewsList(1,val)"
      @current-change="(val: number) => getNewsList(val,limit)"
    />
    <vxe-modal
      v-model="showEdit"
      min-width="600"
      width="1000"
      :show-footer="false"
      height="600"
      :draggable="false"
      @hide="EmptyForm"
    >
      <template #title>
        <span v-if="!AddNus" style="color: red"> 订单详情 </span>
        <span v-else style="color: red">{{
          !formData.id ? "添加数据" : "修改数据"
        }}</span>
      </template>
      <div v-if="!AddNus">
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">用户名:</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              {{ formData.receiverName }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">创建时间：</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              {{ formData.createTime }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">地址</div></el-col
          >
          <el-col :span="21"
            ><div
              class="grid-content ep-bg-purple-light"
              v-html="formData.receiverAddress"
            ></div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">发货状态:</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              {{ formData.status }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">订单列表:</div></el-col
          >
          <el-col :span="21">
            <vxe-table
              v-if="!AddNus"
              border
              align="center"
              :data="formData.orderItems"
            >
              <vxe-column type="seq" title="序号" width="60"></vxe-column>
              <vxe-column field="name" title="商品名称"></vxe-column>
              <vxe-column field="skuNum" title="商品数量"></vxe-column>
              <vxe-column title="商品图片">
                <template #default="{ row }">
                  <img
                    v-if="row.skuImage"
                    v-lazyImg="row.skuImage"
                    style="width: 100px; height: 100px"
                    :src="defaultImg"
                  />
                </template>
              </vxe-column>
              <vxe-column
                align="right"
                field="price"
                title="商品价格"
              ></vxe-column>
            </vxe-table>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="22"
            ><div class="grid-content ep-bg-purple">订单金额:</div></el-col
          >
          <el-col :span="2"
            ><div class="grid-content ep-bg-purple-light">
              {{ "￥" + formData.totalPrice }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="20"></el-col>
          <el-col :span="4">
            <vxe-button
              status="primary"
              content="修改"
              @click="AddNus = true"
            ></vxe-button>
            <vxe-button
              status="primary"
              content="关闭"
              @click="showEdit = false"
            ></vxe-button>
          </el-col>
        </el-row>
      </div>
      <div v-else>
        <el-form
          class="demo-ruleForm"
          :rules="rules"
          :model="formData"
          ref="ruleFormRef"
        >
          <el-form-item label="用户名" prop="receiverName">
            <el-input v-model="formData.receiverName" />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="formData.createTime" />
          </el-form-item>
          <el-form-item label="发货状态" prop="status">
            <el-input v-model="formData.status" />
          </el-form-item>
          <el-form-item label="订单列表" prop="orderItems">
            <div
              v-for="(item, index) in formData.orderItems"
              :key="item.skuId"
              @click="A = index"
            >
              <el-form :rules="items" ref="itemRef" :model="item">
                <el-form-item
                  label="商品名称"
                  prop="name"
                  style="margin: 20px 0"
                >
                  <el-input v-model="item.name" />
                </el-form-item>
                <el-form-item
                  label="商品数量"
                  prop="skuNum"
                  style="margin: 20px 0"
                >
                  <el-input v-model="item.skuNum" />
                </el-form-item>
                <el-form-item
                  label="商品价格"
                  prop="price"
                  style="margin: 20px 0"
                >
                  <el-input v-model="item.price" />
                </el-form-item>
                <el-form-item
                  label="商品图片"
                  prop="skuImg"
                  style="margin: 20px 0"
                >
                  <el-upload
                    class="avatar-uploader"
                    :action="`${BASE_URL}/admin/product/upload`"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <el-icon v-if="uploadLoading" class="avatar-uploader-icon"
                      ><Loading
                    /></el-icon>
                    <img
                      v-else-if="item.skuImage"
                      :src="item.skuImage"
                      class="avatar"
                    />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-form>
            </div>
          </el-form-item>
          <el-form-item label="地址" prop="receiverAddress">
            <quill-editor
              theme="snow"
              toolbar="full"
              contentType="html"
              v-model:content="formData.receiverAddress"
            ></quill-editor>
          </el-form-item>
        </el-form>
        <el-row style="margin: 5px 0">
          <el-col :span="20"></el-col>
          <el-col :span="4">
            <vxe-button status="primary" @click="submitForm(ruleFormRef)">
              确认
            </vxe-button>
            <vxe-button content="默认颜色" @click="showEdit = false"
              >取消</vxe-button
            >
          </el-col>
        </el-row>
      </div>
    </vxe-modal>
  </div>
  <vue3-html2pdf
    :show-layout="false"
    :float-layout="true"
    :enable-download="false"
    :preview-modal="true"
    :paginate-elements-by-height="2500"
    filename="hee hee"
    :pdf-quality="2"
    :manual-pagination="false"
    pdf-format="a4"
    pdf-orientation="landscape"
    pdf-content-width="800px"
    :html-to-pdf-options="htmlToPdfOptions"
    @progress="onProgress($event)"
    @hasStartedGeneration="hasStartedGeneration()"
    @hasGenerated="hasGenerated($event)"
    ref="html2Pdf"
  >
    <template v-slot:pdf-content>
      <vxe-table
        :loading="loading"
        show-overflow
        border="full"
        align="center"
        :row-config="{ isHover: true, height: 100 }"
        :column-config="{ resizable: true }"
        :data="tableData"
      >
        <vxe-column type="seq" title="序号" width="60"></vxe-column>
        <vxe-column field="receiverName" title="用户名" width="80"></vxe-column>
        <vxe-column
          field="createTime"
          title="创建时间"
          width="200"
        ></vxe-column>
        <vxe-column title="地址">
          <template #default="{ row }">
            <div v-html="row.receiverAddress"></div>
          </template>
        </vxe-column>
        <vxe-column field="status" title="发货状态" width="100"></vxe-column
        ><vxe-column
          field="totalPrice"
          title="订单金额"
          width="100"
        ></vxe-column>
      </vxe-table>
    </template>
  </vue3-html2pdf>
</template>
<script lang="ts" setup>
import defaultImg from "@/assets/lazy.gif";
import useList from "@/hooks/useList";
import { Plus, Loading } from "@element-plus/icons-vue";
import { onMounted, reactive, ref, getCurrentInstance } from "vue";
import type { FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import type { UploadProps, FormInstance } from "element-plus";
import NProgress from "nprogress"; // 引入nprogress插件
const { proxy } = getCurrentInstance();
const Progressbars = ref(false);
const generateReport = () => {
  proxy.$refs.html2Pdf.generatePdf();
};
const onProgress = (e) => {
  if (!Progressbars.value) {
    NProgress.start();
    Progressbars.value = true;
  } else {
    NProgress.done();
    Progressbars.value = false;
  }
};
const BASE_URL = import.meta.env.VITE_API_URL;
const A = ref(0);
const htmlToPdfOptions = {
  margin: 0,
};
const itemRef = ref<FormInstance>();
interface goodsModule {
  skuId: number | null;
  name: string;
  price: number | null;
  skuNum: number | null;
  skuImage: string;
}
interface Form {
  id: number | null;
  orderNo: string;
  createTime: string;
  receiverName: string;
  receiverPhone: string;
  receiverAddress: string;
  orderItems: goodsModule[];
  originalPrice: number | null;
  discountAmount: number | null;
  status: string;
  totalPrice: string;
}
// 表单重置初始化
const FormInitData = () => ({
  id: null,
  orderNo: "",
  createTime: "",
  receiverName: "",
  receiverPhone: "",
  receiverAddress: "",
  orderItems: [
    {
      skuId: null,
      name: "",
      price: null,
      skuNum: null,
      skuImage: "",
    },
  ],
  originalPrice: null,
  discountAmount: null,
  status: "",
  totalPrice: "",
});

// 图片上传成功时
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  uploadLoading.value = false;
  formData.orderItems[A.value].skuImage = response.data;
  // 单独对这个表单元素进行校验
  ruleFormRef.value?.validateField("skuImg");
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 对文件格式和尺寸判断
  const isJPGOrPng = ["image/png", "image/jpeg"].indexOf(rawFile.type) !== -1;
  const isLt500K = rawFile.size / 1024 < 500;
  if (!isJPGOrPng) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式！");
    return false;
  }
  if (!isLt500K) {
    ElMessage.error("上传图片大小不能超过500KB!");
    return false;
  }
  uploadLoading.value = true;
  return true;
};
// 表单校验
const rules = reactive<FormRules>({
  receiverName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  status: [{ required: true, message: "请输入发货状态", trigger: "blur" }],
  receiverAddress: [{ required: true, message: "请输入地址", trigger: "blur" }],
});
// 表单校验
const items = reactive<FormRules>({
  name: [{ required: true, message: "请输入商品名", trigger: "blur" }],
  skuNum: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
  price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
});
const ColumnNames = [
  "id",
  "orderNo",
  "createTime",
  "receiverName",
  "receiverPhone",
  "receiverAddress",
  "originalPrice",
  "discountAmount",
  "totalPrice",
  "status",
];
const {
  page,
  limit,
  total,
  loading,
  ruleFormRef,
  formData,
  showEdit,
  AddNus,
  tableData,
  submitForm,
  EmptyForm,
  insertEvent,
  recompose,
  deleteNewsList,
  Details,
  getNewsList,
  uploadLoading,
  exportData,
  xTable,
  exportDataEvent,
} = useList<Form>({ url: "orderInfoList", FormInitData, ColumnNames });
onMounted(() => {
  getNewsList(1, limit.value);
});
</script>
<script lang="ts">
import Vue3Html2pdf from "vue3-html2pdf";
export default {
  components: {
    Vue3Html2pdf,
  },
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader :deep(.el-upload:hover) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
